package com.atguigu.spzx.user.service.impl;

import cn.hutool.http.server.HttpServerRequest;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.service.exception.GuiguException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.common.util.IpUtil;
import com.atguigu.spzx.model.dto.user.UserLoginDto;
import com.atguigu.spzx.model.dto.user.UserRegisterDto;
import com.atguigu.spzx.model.entity.h5.UserCollect;
import com.atguigu.spzx.model.entity.h5.UserInfo;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.UserCollectVo;
import com.atguigu.spzx.model.vo.user.UserInfoVo;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: UserInfoServiceImpl
 * @Package: com.atguigu.spzx.user.service.impl
 * @Description
 * @Author 孤妤
 * @Date: 2023/12/19 11:51
 */
@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void userRegist(UserRegisterDto userRegisterDto) {
        String code = userRegisterDto.getCode();
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        // 验空
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password) || StringUtils.isEmpty(nickName)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        // 校验验证码
        String redisCode = redisTemplate.opsForValue().get("user:code:" + username);
        if (!code.equals(redisCode)){
            throw new GuiguException(ResultCodeEnum.CODE_ERROR);
        }
        // 删除验证码
        redisTemplate.delete("user:code:"+username);
        // 查询数据库用户名是否存在
        UserInfo userInfo = userInfoMapper.selectUsernameByUsername(username);
        if (userInfo!=null){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        UserInfo userInfoRegist = new UserInfo();
        userInfoRegist.setUsername(username);
        userInfoRegist.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfoRegist.setNickName(nickName);
        userInfoRegist.setAvatar("http://localhost:9000/spzx/2023/12/08/e458b33cebb34381bb1c391fdfd22b14.gif");
        userInfoRegist.setSex(1);
        userInfoRegist.setPhone(username);
        userInfoRegist.setStatus(1);
        // 添加到数据库中
        userInfoMapper.insertUserRegist(userInfoRegist);
    }

    @Override
    public String userLogin(UserLoginDto userLoginDto, HttpServletRequest request) {
        // 获取用户登录参数
        String password = userLoginDto.getPassword();
        String username = userLoginDto.getUsername();
        // 验空
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        // 根据用户名获取用户
        UserInfo userInfoByUsername = userInfoMapper.selectUserInfoByUsername(username);
        // 该用户是否存在
        if (userInfoByUsername==null){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_NOT_EXSIT);
        }
        // 该用户是否停用
        if (userInfoByUsername.getStatus()==0){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // 校验密码
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(userInfoByUsername.getPassword())){
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        // 获取用户当前ip地址
        String ipAddress = IpUtil.getIpAddress(request);
        // 给用户设置最后登陆的ip地址
        userInfoByUsername.setLastLoginIp(ipAddress);
        // 给用户设置最后登录的时间
        userInfoByUsername.setLastLoginTime(new Date());
        // 新建一个对象提高sql性能
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userInfoByUsername.getId());
        userInfo.setLastLoginIp(ipAddress);
        userInfo.setLastLoginTime(new Date());
        // 更改用户信息
        userInfoMapper.updateUserInfo(userInfo);
        // 获取token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        // 将userInfo对象转为json
        String userInfoStr = JSONObject.toJSONString(userInfoByUsername);
        // 将用户信息存入redis中
        redisTemplate.opsForValue().set("user:login:"+token,userInfoStr,2, TimeUnit.HOURS);
        return token;
    }
    @Override
    public UserInfoVo findUser() {
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }

    @Override
    @Transactional(readOnly = true)
    public Boolean findIsCollect(Integer skuId) {
        UserCollect userCollect = userInfoMapper.selectIsCollect(skuId);
        if (userCollect!=null) return true;
        return false;
    }

    @Override
    public void addCollect(Integer skuId) {
        // 获取当前用户
        Long userId = getUserId();
        userInfoMapper.insertCollect(skuId,userId);
    }

    private Long getUserId() {
        // 获取当前用户id
        return AuthContextUtil.getUserInfo().getId();
    }

    @Override
    public void removeCancelCollect(Integer skuId) {
        userInfoMapper.deleteCancelCollect(skuId);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<UserCollectVo> findUserCollectPage(Integer page, Integer limit) {
        // 获取用户id
        Long userId = getUserId();
        PageHelper.startPage(page,limit);
        List<UserCollectVo> userCollectVoList = userInfoMapper.selectUserCollectPage(userId);
        return new PageInfo<>(userCollectVoList);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<UserCollectVo> findUserBrowseHistoryPage(Integer page, Integer limit) {
        Long userId = getUserId();
        PageHelper.startPage(page,limit);
        List<UserCollectVo> userCollectVoList = userInfoMapper.selectUserBrowseHistoryPage(userId);
        return new PageInfo<>(userCollectVoList);
    }
}
